package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        //2.符合创建6位的验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到session ->redis 2分钟有效
        //session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.调用服务发送验证码到手机上
        log.debug("手机验证码发送成功，code={}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();


        //1.检验手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式不正确");
        }
        //2.获取校验码
        String codeCache =stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        if (codeCache == null) {
            return Result.fail("验证码为空！");
        }
        //3、校验验证码是否匹配
        if(code == null || !codeCache.equals(code)){
            return Result.fail("验证码不正确");
        }
        //3.查询用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //4、如果用户不存在，创建新用户
            user = new User();
            user.setPhone(phone);
            user.setIcon("icon");
            user.setPassword(RandomUtil.randomNumbers(8));
            user.setNickName("user_"+RandomUtil.randomString(10));
            save(user);
        }
        //生成token作为登录令牌，保存到redis中，并返回给前端token
        String uuid = UUID.randomUUID().toString(true);
        //user对象转hashMap 但是id是long类型，stringredistemplate接收的都是string类型的。
        //Map<String, Object> userMap = BeanUtil.beanToMap(user);
        //Map<String, Object> userMap = BeanUtil.beanToMap(user,new HashMap<>(),
        //        CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id",user.getId().toString());
        userMap.put("phone",user.getPhone());
        userMap.put("icon",user.getIcon());
        userMap.put("password",user.getPassword());
        userMap.put("nickName",user.getNickName());
        userMap.put("createTime",user.getCreateTime().toString());
        userMap.put("updateTime",user.getUpdateTime().toString());
        //保存用户到redis中 并设置有效期
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+uuid, userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY+uuid,LOGIN_USER_TTL,TimeUnit.SECONDS);
        return Result.ok(uuid);
    }

    @Override
    public Result sign() {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //获取当前是这个月的第几天
        int day = now.getDayOfMonth();
        //拼接key
        String key = USER_SIGN_KEY+userId+format;
        //保存签到信息
        stringRedisTemplate.opsForValue().setBit(key,day-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //获取当前是这个月的第几天
        int day = now.getDayOfMonth();
        //拼接key
        String key = USER_SIGN_KEY+userId+format;

        List<Long> longs = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));
        if (longs == null || longs.isEmpty())  {
            return Result.ok(0);
        }

        Long num = longs.get(0);
        if (num == 0 || num== null) {
            return Result.ok(0);
        }
        int count = 0 ;
        //循环遍历
        while (true){
            //让这个数字与1做与运算 ，得到数字的最后一个bit位。如果是0 说明没签到
            if((num & 1) == 0){
                break;
            }else {
                count++;
            }
            //把数字右移一位，抛弃最后一个bit位。继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }
}
